<template>
  <el-dialog
    v-model="dialogVisible"
    :title="assignType === 'survey' ? '调查分配' : '采样分配'"
    append-to-body
    destroy-on-close
    width="800px"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <!-- 上半部分：项目基本信息 -->
      <div class="info-section">
        <div class="section-title">项目基本信息</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectNo">
              <el-input v-model="formData.projectNo" class="!w-240px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="受检单位" prop="receivingUnit">
              <el-input v-model="formData.receivingUnit" class="!w-240px" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采样天数" prop="sampleDays">
              <el-input v-model="formData.sampleDays" class="!w-240px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-input v-model="formData.projectType" class="!w-240px" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目负责人" prop="projectManager">
              <el-input v-model="formData.projectManager" class="!w-240px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="当前状态" prop="status">
              <el-input v-model="formData.status" class="!w-240px" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 下半部分：调查分配信息 -->
      <div class="assign-section">
        <div class="section-title">{{
          assignType === 'survey' ? '调查分配信息' : '采样分配信息'
        }}</div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              :label="assignType === 'survey' ? '调查日期' : '采样日期'"
              prop="surveyDate"
            >
              <el-date-picker
                v-model="formData.surveyDate"
                class="!w-240px"
                :placeholder="assignType === 'survey' ? '请选择安排调查日期' : '请选择安排采样日期'"
                type="date"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              :label="assignType === 'survey' ? '调查负责人' : '采样负责人'"
              prop="investigator"
            >
              <el-input
                v-model="formData.investigatorName"
                class="!w-240px custom-input"
                :placeholder="assignType === 'survey' ? '双击选择调查负责人' : '双击选择采样负责人'"
                readonly
                @dblclick="handleSelectLeader"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              :label="assignType === 'survey' ? '调查组人员' : '采样组人员'"
              prop="investigatorTeamsList"
            >
              <div class="tag-wrapper !w-240px custom-input" @dblclick="handleSelectTeams">
                <el-tag
                  v-for="(tag, index) in formData.investigatorTeamsNameList"
                  :key="formData.investigatorTeamsList[index]"
                  class="mx-1"
                  closable
                  @close="handleRemoveTeamMember(tag, index)"
                >
                  {{ tag }}
                </el-tag>
                <div v-if="formData.investigatorTeamsNameList.length === 0" class="placeholder">
                  {{ assignType === 'survey' ? '双击选择调查组人员' : '双击选择采样组人员' }}
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>

    <!-- 修改人员选择弹窗 -->
    <el-dialog
      v-model="userSelectVisible"
      :title="userSelectTitle"
      append-to-body
      destroy-on-close
      width="80%"
    >
      <SystemUser
        :multiple="isMultiple"
        :selectable="true"
        :default-selected-ids="formData.investigatorTeamsList"
        @cancel="userSelectVisible = false"
        @select="handleUserSelect"
        :confirm-text="assignType === 'survey' ? '添加调查人员' : '添加采样人员'"
      />
    </el-dialog>
  </el-dialog>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { ProjectApi, ProjectVO } from '@/api/dk/project'
import SystemUser from '@/views/system/user/index.vue'
import * as UserApi from '@/api/system/user'

const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

const formData = ref({
  id: '',
  projectNo: '',
  receivingUnit: '',
  sampleDays: '',
  projectType: '',
  projectManager: '',
  investigator: '',
  investigatorName: '',
  investigatorTeamsList: [] as string[],
  investigatorTeamsNameList: [] as string[],
  surveyDate: '',
  status: '待分配'
})

// 修改验证规则
const formRules = computed(() => ({
  investigator: [
    {
      required: true,
      message: assignType.value === 'survey' ? '请选择调查负责人' : '请选择采样负责人',
      trigger: 'submit' // 只在提交时触发验证
    }
  ],
  investigatorTeamsList: [
    {
      required: true,
      message: assignType.value === 'survey' ? '请选择调查组人员' : '请选择采样组人员',
      trigger: 'submit' // 只在提交时触发验证
    }
  ],
  surveyDate: [
    {
      required: true,
      message: assignType.value === 'survey' ? '请选择调查日期' : '请选择采样日期',
      trigger: 'submit' // 只在提交时触发验证
    }
  ]
}))

// 添加分配类型
const assignType = ref<'survey' | 'sample'>('survey')

/** 打开弹窗 */
const open = async (row: ProjectVO, type: 'survey' | 'sample') => {
  dialogVisible.value = true
  assignType.value = type // 设置分配类型

  // 加载项目详情数据
  try {
    // 获取最新的项目数据
    const projectData = await ProjectApi.getProject(row.id)

    // 根据类型获取不同的字段
    const typeFields = {
      survey: {
        investigator: projectData.investigator,
        teams: projectData.investigatorTeams,
        date: projectData.surveyDate
      },
      sample: {
        investigator: projectData.sampleInvestigator,
        teams: projectData.sampleTeams,
        date: projectData.sampleDate
      }
    }[type]

    // 设置基本表单数据
    formData.value = {
      id: projectData.id,
      projectNo: projectData.projectNo || '',
      receivingUnit: projectData.receivingUnit || '',
      sampleDays: projectData.day?.toString() ?? '',
      projectType: projectData.projectType || '',
      projectManager: projectData.projectManager || '',
      investigator: typeFields.investigator || '',
      investigatorName: '',
      investigatorTeamsList: typeFields.teams ? typeFields.teams.split(',') : [],
      investigatorTeamsNameList: [],
      surveyDate: typeFields.date || '',
      status: projectData.status || '待分配'
    }

    // 获取负责人信息
    if (typeFields.investigator) {
      try {
        const investigatorInfo = await UserApi.getUser(Number(typeFields.investigator))
        formData.value.investigatorName = investigatorInfo.nickname
      } catch (error) {
        console.error('获取负责人信息失败:', error)
      }
    }

    // 获取项目负责人名称
    if (projectData.projectManager) {
      try {
        const pmInfo = await UserApi.getUser(Number(projectData.projectManager))
        formData.value.projectManager = pmInfo.nickname
      } catch (error) {
        console.error('获取项目负责人信息失败:', error)
      }
    }

    // 获取组成员信息
    if (formData.value.investigatorTeamsList.length > 0) {
      try {
        const nameList: string[] = []
        for (const userId of formData.value.investigatorTeamsList) {
          const userInfo = await UserApi.getUser(Number(userId))
          nameList.push(userInfo.nickname)
        }
        formData.value.investigatorTeamsNameList = nameList
      } catch (error) {
        console.error('获取组成员信息失败:', error)
      }
    }
  } catch (error) {
    message.error('获取项目信息失败')
    dialogVisible.value = false
  }
}

// 提交表单
const emit = defineEmits(['success'])
const message = useMessage()

const submitForm = async () => {
  if (!formRef.value) return
  try {
    // 手动触发表单验证
    await formRef.value.validate()

    // 准备提交数据
    const submitData = {
      id: formData.value.id,
      type: assignType.value,
      ...(assignType.value === 'survey'
        ? {
            investigator: formData.value.investigator,
            investigatorTeams: formData.value.investigatorTeamsList.join(','),
            surveyDate: formData.value.surveyDate
          }
        : {
            sampleInvestigator: formData.value.investigator,
            sampleTeams: formData.value.investigatorTeamsList.join(','),
            sampleDate: formData.value.surveyDate
          })
    }
    if (assignType.value === 'survey') {
      await ProjectApi.surveyAllocation(submitData)
    }else {
      await ProjectApi.samplingAllocation(submitData)
    }
    message.success(assignType.value === 'survey' ? '调查分配成功' : '采样分配成功')
    dialogVisible.value = false
    emit('success')
  } catch {
    // 验证失败时不需要额外提示,表单会自动显示错误信息
    return
  }
}

// 人员选择相关
const userSelectVisible = ref(false)
const userSelectTitle = ref('')
const isMultiple = ref(false)
const selectType = ref<'leader' | 'teams'>('leader')

// 打开选择调查负责人弹窗
const handleSelectLeader = () => {
  userSelectVisible.value = true
  userSelectTitle.value = assignType.value === 'survey' ? '选择调查负责人' : '选择采样负责人'
  isMultiple.value = false
  selectType.value = 'leader'
}

// 打开选择调查组人员弹窗
const handleSelectTeams = () => {
  userSelectVisible.value = true
  userSelectTitle.value = assignType.value === 'survey' ? '选择调查组人员' : '选择采样组人员'
  isMultiple.value = true
  selectType.value = 'teams'
}

// 处理人员选择
const handleUserSelect = (users: any) => {
  if (selectType.value === 'leader') {
    // 单选：调查负责人
    formData.value.investigator = users.id
    formData.value.investigatorName = users.nickname
    userSelectVisible.value = false
  } else {
    // 多选：调查组人员
    if (Array.isArray(users)) {
      formData.value.investigatorTeamsList = users.map((user) => user.id)
      formData.value.investigatorTeamsNameList = users.map((user) => user.nickname)
      userSelectVisible.value = false
    }
  }
}

// 处理删除调查组成员
const handleRemoveTeamMember = (tag: string, index: number) => {
  formData.value.investigatorTeamsList.splice(index, 1)
  formData.value.investigatorTeamsNameList.splice(index, 1)
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.info-section,
.assign-section {
  position: relative;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;

  .section-title {
    position: absolute;
    top: -12px;
    left: 10px;
    padding: 0 10px;
    background-color: #fff;
    font-size: 14px;
    color: #606266;
  }
}

.assign-section {
  margin-top: 30px;
}

// 统一的输入框样式
.custom-input {
  :deep(.el-input__wrapper),
  &.tag-wrapper {
    cursor: pointer;
    background-color: var(--el-fill-color-light);
    &:hover {
      background-color: var(--el-fill-color); // 添加悬停效果
    }
  }
}

.tag-wrapper {
  min-height: 32px;
  padding: 1px 11px;
  border-radius: 4px;
  border: 1px solid var(--el-border-color);
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;

  .placeholder {
    color: var(--el-text-color-placeholder);
    font-size: 14px;
  }

  .el-tag {
    margin: 2px 0;
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary-light-8);
    color: var(--el-color-primary);

    .el-tag__close {
      color: var(--el-color-primary);
      &:hover {
        background-color: var(--el-color-primary);
        color: white;
      }
    }
  }
}

// 移除旧的样式
.el-input.readonly {
  :deep(.el-input__wrapper) {
    cursor: pointer;
    background-color: var(--el-fill-color-light);
  }
}
</style>
